﻿using System.Threading.Tasks;
using System;
using ERP.EntityFrameworkCore;
using ERP.QualityAssurance;
using ERP.QualityAssurance.Dto;
using Microsoft.AspNetCore.Mvc;

namespace ERP.Web.Controllers
{
    public class HolidaySettingModelController : Controller
    {
        private readonly IHolidaySettingServices _holidaySettingServices;

        public HolidaySettingModelController(IHolidaySettingServices holidaySettingServices)
        {
            _holidaySettingServices = holidaySettingServices;
        }

        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 添加/修改节假日设置视图页面
        /// </summary>
        [HttpGet]
        public IActionResult AddOrEdit(string date)
        {
            return View();
        }

        /// <summary>
        /// 获取节假日设置数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetHolidaySettings(int year, int month)
        {
            try
            {
                var startDate = new DateTime(year, month, 1);
                var endDate = startDate.AddMonths(1).AddDays(-1);

                System.Diagnostics.Debug.WriteLine($"查询节假日数据: {year}年{month}月 ({startDate:yyyy-MM-dd} 到 {endDate:yyyy-MM-dd})");

                var holidays = await _holidaySettingServices.GetHolidaySettingsAsync(startDate, endDate);

                System.Diagnostics.Debug.WriteLine($"找到 {holidays.Count} 条节假日数据");
                foreach (var holiday in holidays)
                {
                    System.Diagnostics.Debug.WriteLine($"  {holiday.HolidayDate:yyyy-MM-dd} = {(holiday.HolidayType == 0 ? "假" : "班")}");
                }

                return Ok(new
                {
                    success = true,
                    data = holidays,
                    message = "获取成功"
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取节假日数据失败: {ex.Message}");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 获取指定日期的节假日设置
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetHolidayByDate(string date)
        {
            try
            {
                if (DateTime.TryParse(date, out DateTime targetDate))
                {
                    var holiday = await _holidaySettingServices.GetHolidaySettingByDateAsync(targetDate);

                    return Ok(new
                    {
                        success = true,
                        data = holiday,
                        message = "获取成功"
                    });
                }
                else
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "日期格式错误"
                    });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 保存节假日设置
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> SaveHolidaySetting([FromBody] CreateOrUpdateHolidaySettingDto input)
        {
            try
            {
                if (input == null)
                {
                    System.Diagnostics.Debug.WriteLine("输入参数为空");
                    return BadRequest(new { success = false, message = "保存失败：参数为空" });
                }

                System.Diagnostics.Debug.WriteLine($"接收到保存节假日数据，日期: {input.HolidayDate}, 类型: {input.HolidayType}");
                
                // 确保日期值有效
                if (input.HolidayDate.Year < 2000 || input.HolidayDate.Year > 2050)
                {
                    System.Diagnostics.Debug.WriteLine($"日期值超出合理范围: {input.HolidayDate}");
                    return BadRequest(new { success = false, message = "保存失败：日期值无效" });
                }
                
                var result = await _holidaySettingServices.CreateOrUpdateAsync(input);
                System.Diagnostics.Debug.WriteLine($"节假日保存成功，ID：{result.Id}，日期：{result.HolidayDate:yyyy-MM-dd}");

                return Ok(new
                {
                    success = true,
                    data = result,
                    message = "保存成功"
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存节假日设置失败: {ex}");
                return StatusCode(500, new
                {
                    success = false,
                    message = "保存失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 删除节假日设置
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteHolidaySetting([FromBody] DeleteHolidaySettingDto input)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"删除节假日设置，日期: {input.Date}");
                
                if (DateTime.TryParse(input.Date, out DateTime targetDate))
                {
                    await _holidaySettingServices.DeleteByDateAsync(targetDate);
                    System.Diagnostics.Debug.WriteLine($"删除节假日设置成功，日期: {targetDate:yyyy-MM-dd}");

                    return Ok(new
                    {
                        success = true,
                        message = "删除成功"
                    });
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"删除节假日设置失败，无效的日期格式: {input.Date}");
                    return BadRequest(new
                    {
                        success = false,
                        message = "日期格式错误"
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"删除节假日设置失败: {ex}");
                return StatusCode(500, new
                {
                    success = false,
                    message = "删除失败：" + ex.Message
                });
            }
        }
    }

    public class DeleteHolidaySettingDto
    {
        public string Date { get; set; }
    }
}
